package com.gopay.bis.web.controller.ebank;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.bis.domain.order.OrderInfo;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.PayEaseConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.payease.ebank.PayEaseMessage;

/**
 * 首信通道前台通知
 * 
 * @UmPayServerRes.java
 * @author liuzhp
 * @2013-12-4 下午5:23:49 www.gopay.com.cn Inc.All rights reserved.
 */
@Controller
@Scope("prototype")
public class PayEasePayServerRes extends BankResBase {
	
	private static Log logger = LogFactory.getLog(PayEasePayServerRes.class);
	private int pendingOrderNum; 	//待处理的订单数
	private int totalOrderNum;		//总订单数
	private int index;				//多笔处理时，正在处理的订单索引
	
	@RequestMapping(value = "/payEasePayServerRes")
	protected ModelAndView execute(HttpServletRequest request,HttpServletResponse response) {
		logger.error("--------------- PayEasePayServerRes bankback  ---------------");
		String v_oid = request.getParameter("v_oid");
		ModelAndView view = null;	
		try {
			if (StringUtils.isEmpty(v_oid)) {
				logger.error("PayEasePayServerRes bankback error：orderid:"+v_oid);
				OutputStream out = null;
				try {
					out = response.getOutputStream();
					out.write("error".getBytes("UTF-8"));
				} catch (Exception e) {
				} finally{
					if(out != null) out.close();
				}
			}
			
			totalOrderNum = v_oid.split("[|][_][|]").length;
			this.pendingOrderNum = totalOrderNum;
			
			
			for(int i=0; i<pendingOrderNum;){
				logger.error(String.format("payease多笔返回 , v_oid=%s, num=%s",v_oid,pendingOrderNum));
				view = super.execute(request, response);
				pendingOrderNum--;
			}
			
		} catch (Exception e) {
			logger.error("PayEasePayServerRes bankback error：orderid:"+v_oid, e);
		}
		return view;
	}

	@Override
	protected BaseMessage buildMessage(HttpServletRequest request) {
		/**
		 * 因银行会多笔返回，但验签是统一验签，国付宝单笔入账，故验签参数统一，对订单号、交易结果等参数进行拆分
		 */
		String v_oid = request.getParameter("v_oid");
		String v_pstatus = request.getParameter("v_pstatus");
		String v_amount = request.getParameter("v_amount");
		String v_moneytype = request.getParameter("v_moneytype");
		String v_count = request.getParameter("v_count");
		
		PayEaseMessage msg = new PayEaseMessage();
		msg.setPlainMessage(v_oid + v_pstatus + v_amount + v_moneytype + v_count);
		msg.setVsign(request.getParameter("v_sign"));
		
		index = totalOrderNum - pendingOrderNum;
		String split = "[|][_][|]";
		msg.setOrderId(v_oid.split(split)[index].split("-")[2]);
		msg.setBankOrderId(v_oid.split(split)[index]);
		msg.setVpstatus(v_pstatus.split(split)[index]);
		msg.setVpmode(request.getParameter("v_pmode"));
		msg.setVpstring(request.getParameter("v_pstring"));
		msg.setVamount(v_amount.split(split)[index]);
		msg.setSignMessage(request.getParameter("v_md5money"));
		msg.setVmoneytype(v_moneytype.split(split)[index]);
		msg.setFront(false);	
		msg.setBankBusProd(BisBankBusinessProd._00);
		//后台通知，接口返回码跟交易成功定义码转换
		msg.setVpstatus(("1".equals(msg.getVpstatus()) ? "20" : "30"));
		
		return msg;
	}

	@Override
	protected OrderInfo buildOrderInfo(HttpServletRequest request, Result result) {
		logger.error("PAYEASE SERVER:"+ ToStringBuilder.reflectionToString((PayEaseMessage)result.getModel("message")));
		OrderInfo orderInfo = new OrderInfo();
		PayEaseMessage easeMessage = (PayEaseMessage) result.getModel("message");
		if(easeMessage!=null){
			String trade_state = request.getParameter("v_pstatus").split("[|][_][|]")[index];
			if (trade_state != null&& trade_state.equals(PayEaseConstants.QUERY_VPSTATUS_SUCCESS)) {
				orderInfo.setOrderId(easeMessage.getOrderId());
				orderInfo.setAmt(easeMessage.getVamount());
				orderInfo.setNotifyNum("1");
				orderInfo.setPayStatus("00");
				orderInfo.setRetCode("00");
				orderInfo.setRetMsg("支付成功");
			} else {
				orderInfo.setOrderId(easeMessage.getOrderId());
				orderInfo.setAmt(easeMessage.getVamount());
				orderInfo.setNotifyNum("1");
				orderInfo.setPayStatus("01");
				orderInfo.setRetCode("01");
				orderInfo.setRetMsg("");
			}
		}
		orderInfo.setCardType("Unknown");
		//多笔返回时，最后一笔处理后通知银行，响应银行
		if(this.pendingOrderNum == 1)
			orderInfo.setIsNotify(true);	
		orderInfo.setBankName("payease");
		return orderInfo;
	}

	@Override
	protected boolean checkParameters(HttpServletRequest request) {
		if (StringUtils.isEmpty(request.getParameter("v_oid"))
			|| StringUtils.isEmpty(request.getParameter("v_pstatus"))
			|| StringUtils.isEmpty(request.getParameter("v_amount"))) {
		return false;
		}
		return true;
	}
	
}
